package org.hzero.business;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 得到文件中的值
 * Created by yufeng.liu@hand.com on 2018/3/28.
 */
public class KnifePropertyUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(KnifePropertyUtil.class);

    private static final String FILE_READ_ERROR = "文件读取异常{}";

    private static final String DEFAULT_FILE_NAME = "config.properties";

    /**
     * 通过键从对应的属性文件中得到值
     * @param key 要获取值的键
     * @param propertyFileName 要获取值对应的属性文件名
     * @param clazz 类
     * @return 返回值
     */
    public static String getValueByKey(String key, String propertyFileName, Class clazz) {
        InputStream inStream = clazz.getClassLoader().getResourceAsStream(propertyFileName);
        Properties prop = new Properties();
        try {
            prop.load(inStream);
            return prop.getProperty(key);
        } catch (IOException e) {
            LOGGER.error(FILE_READ_ERROR, e.getMessage());
        }
        return null;
    }

    /**
     * 默认从application.properties属性文件中得到值
     * @param key 要获取值的键
     * @param clazz 类
     * @return 返回值
     */
    public static String getValueByKey(String key, Class clazz) {
        InputStream inStream = clazz.getClassLoader().getResourceAsStream(DEFAULT_FILE_NAME);
        Properties prop = new Properties();
        try {
            prop.load(inStream);
            return prop.getProperty(key);
        } catch (IOException e) {
            LOGGER.error(FILE_READ_ERROR, e.getMessage());
        }
        return null;
    }


    /**
     * 解析形如:"${SPRING_REDIS_PASSWORD:  hzero@2020 }"格式的数据
     * @param key 要获取值的键
     * @return 返回值
     */
    public static String getSpecialValueByKey(String key) {
        if (key.matches("\\$\\{[\\s\\S]*:[\\s\\S]*}")){
            int i = key.indexOf(":");
            int j = key.lastIndexOf("}");
            key = key.substring(i+1, j).trim();
        }
        return key;
    }
}
